import { useService, useStore } from '@/hooks';
import { Button, Checkbox, Dialog, Field, Form, Input, Message } from '@alifd/next';
import { observable } from 'mobx';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid } from '../stores/definitions';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { observer } from 'mobx-react-lite';
import MapModal from '@/components/MapModal';
import { deconstructionMapObj, strTransferNumber, arrTransferStr } from '@/utils/util';

const FromItem = Form.Item;
const formItemLayout = {
  labelCol: {
    fixedSpan: 8,
  },
  wrapperCol: {
    span: 14,
  },
  style: { marginBottom: 20 },
};

const RegionForm = ({ regionId, parentId, modal, onSubmit, onCancel }) => {
  const { regionStore: store } = useStore();
  const [isViewMode] = useState(modal[0] === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const [region] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [useTownCode, setUseTownCode] = useState(false);
  const { apiLbs } = useService();
  const [map, setMap] = useState({ show: false, coord: '', cityName: '' });

  // 重载definitions中的定义，处理一些根据上下文的动态定义
  const overrideModel = {
    extras: {
      long_lat: {
        value: {
          ui: {
            renderer: (v) => (<Input
              value={v}
              placeholder={t`选择经纬度`}
              addonAfter={isViewMode ? null : <Button type="primary" onClick={() => handleMapOpen(v)}>{t`获取经纬度`}</Button>}
            />),
            itemProps: { required: true },
          },
        },
      },
      adcode: {
        value: {
          ui: {
            renderer: (v) => (<Input
              value={v}
              placeholder={t`选择经纬度`}
              addonAfter={(isViewMode || !parentId) ? null : <Checkbox checked={useTownCode} onClick={toggleTownCode} style={{ marginLeft: 15 }} >{t`四级行政区划`}</Checkbox>}
            />),
            itemProps: { required: true },
          },
        },
      },
    },
  };

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      if (regionId) {
        const data = await store.get(regionId);
        editCtx.origin = _.cloneDeep(data);
        _.assign(region, { ...data, disabled: !data.disabled });
        if (data?.extras?.adcode?.value?.length === 9) {
          setUseTownCode(true);
        }
      } else {
        // 添加操作
        _.set(region, 'parentId', parentId);
        const nextId = await store.nextId(parentId);
        if (parentId) { // 添加区域
          _.set(region, 'itemId', `${store.cityId}${(`${nextId}`).padStart(3, '0')}`); // 这里是编号生成规则
        } else { // 添加城市
          _.set(region, 'itemId', `${(`${nextId}`).padStart(3, '0')}`); // 这里是编号生成规则
        }
        _.set(region, 'sortWeight', 1);
      }
    })();
  }, []);

  if (!region) return <></>;

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(region, name, value);
    // 联动效果可以在这里通过设置region属性实现

    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
    // console.log('form data: ', name, value, toJS(region));
  };

  const handleMapOpen = async (v) => {
    const { parentId: _parentId, name } = toJS(region);

    if (!v && !name) {
      Message.warning(t`请先设置名称`);
      return;
    }
    let coord = v;
    const currentCity = store._city[parentId];
    if (!v) {
      const r = await apiLbs.placeSearch({ region: currentCity, keyword: region.name });
      const { location } = r[0];
      if (location) coord = arrTransferStr(location);
    }
    if (parentId) { // 处理区域
      setMap({ show: true, coord, cityName: currentCity });
    } else { // 处理城市
      try {
        const res = await apiLbs.placeSearch({ region: currentCity, keyword: region.name });
        const { location, adcode } = res[0];
        const _location = arrTransferStr(location);
        _.set(region, 'extras.long_lat.value', _location);
        _.set(region, 'extras.adcode.value', adcode);
      } catch (e) {
        Message.error({ content: t`获取位置信息失败` });
      }
    }
  };

  const handleCoordPicked = async (coord) => {
    const { lat, lng } = toJS(coord);
    const location = deconstructionMapObj(toJS(coord));
    _.set(region, 'extras.long_lat.value', location);
    // 根据fullId层级来判断是否是区级行政区 如果存在或者分割后长度为2 则为行政区 否则为站点
    const { adcode } = await apiLbs.lbsGeocoder({ coord: [lng, lat] });
    _.set(region, 'extras.adcode.value', adcode);

    setMap({ show: false });
  };

  // 获取四级行政区划代码
  const toggleTownCode = async () => {
    const long_lat = _.get(region, 'extras.long_lat.value');

    if (!long_lat) {
      Message.error('请先选取经纬度');
      return;
    }
    const { lat, lng } = strTransferNumber(long_lat);
    const { adcode, townCode } = await apiLbs.lbsGeocoder({ coord: [lat, lng] });

    if (useTownCode) {
      _.set(region, 'extras.adcode.value', adcode);
      setUseTownCode(false);
    } else if (townCode) {
      _.set(region, 'extras.adcode.value', townCode);
      setUseTownCode(true);
    } else {
      Message.warning({ content: t`所选坐标未包含四级行政区划编码` });
      _.set(region, 'extras.adcode.value', adcode);
      setUseTownCode(false);
    }
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => { v !== undefined && (r[k] = v); }))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (value, errors, _field) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: RegionForm.jsx:173 _ errors:', errors);
      return;
    }
    _.set(region, 'disabled', !region.disabled);
    onSubmit?.(region);
  };

  return (
    <Form
      isPreview={isViewMode}
      {...formProps}
      value={region}
      colon
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <FieldsGrid
        formData={region}
        overrideModel={overrideModel}
        itemLayout={{ ...formItemLayout, labelAlign: 'left' }}
        mode={modal[0]}
        columns={1}
        fields={((modal[0] === 'add' || isViewMode) ? ['itemId'] : []).concat(['name', 'sortWeight', 'disabled', 'extras.long_lat.value', 'extras.adcode.value', 'extras.hot.value', 'description'])}
      />
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
      <MapModal
        visible={map.show}
        coord={map.coord}
        cityName={map.cityName}
        containerId={'regionForm'}
        onClose={() => setMap({ show: false })}
        onCancel={() => setMap({ show: false })}
        onPick={handleCoordPicked}
      />
    </Form>
  );
};

export default observer(RegionForm);
